package cn.imvc.core;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class SpringFilter implements Filter {
	private ServletContext servletContext;

	public void init(FilterConfig filterConfig) throws ServletException {
		servletContext = filterConfig.getServletContext();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (servletContext.getAttribute("rootUrl") == null) {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			String webPort = String.valueOf(request.getServerPort());
			if (webPort.equals("80")) {
				webPort = "";
			}
			String rootUrl = httpRequest.getScheme() + "://"
					+ httpRequest.getServerName() + ":" + webPort
					+ httpRequest.getContextPath();
			servletContext.setAttribute("rootUrl", rootUrl);
			servletContext.setAttribute("rootPath",
					servletContext.getRealPath("/"));
		}
		request.setAttribute("_ServletResponse_",response);
		chain.doFilter(request, response);
	}

	public void destroy() {
		servletContext = null;
	}

}
